package com.zusmart.core.config.source;

import java.util.HashMap;
import java.util.Map;

import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.zusmart.base.util.Assert;
import com.zusmart.core.config.support.AbstractConfigSource;

public class ConfigSourceForXml extends AbstractConfigSource {

	public static final String EXTENSION = "xml";

	private final Element element;
	private final Map<String, String> cached = new HashMap<String, String>();

	public ConfigSourceForXml(String configFile, Element element) {
		super(configFile, EXTENSION);
		Assert.isNull(element, "element must not be null");
		this.element = element;
	}

	@Override
	public boolean hasConfigData(String configName) {
		return this.getNodeValue(configName) != null;
	}

	@Override
	public String getConfigData(String configName, String defaultData) {
		String result = this.getNodeValue(configName);
		if (null == result) {
			return defaultData;
		}
		return result;
	}

	protected String getNodeValue(String configName) {
		if (this.cached.containsKey(configName)) {
			return this.cached.get(configName);
		}
		String[] names = null;
		if (configName.indexOf(".") != -1) {
			names = configName.split("\\.");
		} else {
			names = new String[] { configName };
		}
		if (null == names || names.length == 0) {
			return null;
		}
		NodeList nodeList = this.element.getChildNodes();
		if (null == nodeList || nodeList.getLength() == 0) {
			return null;
		}
		String result = null;
		NodeList tempList = nodeList;
		for (int i = 0; i < names.length; i++) {
			String name = names[i];
			if (null != tempList && tempList.getLength() > 0) {
				for (int j = 0; j < tempList.getLength(); j++) {
					Node node = tempList.item(j);
					if (name.equals(node.getNodeName())) {
						if (i == names.length - 1) {
							result = node.getTextContent();
							break;
						} else {
							tempList = node.getChildNodes();
						}
					}
				}
			}
		}
		return result;
	}

}